Page({
  data: {
    labels: '',
    rank: '',
    region: '',
    sex: '',
    way: '',
    searchResults: [],
    loading: false,
    error: null
  },

  onLoad: function(options) {
    try {
      const rawData = {};
      for (let key in options) {
        rawData[key] = decodeURIComponent(options[key]);
      }
      
      this.setData({
        labels: rawData.labels || '全部',
        rank: rawData.rank || '',
        region: rawData.region || '',
        sex: rawData.sex || '',
        way: rawData.way || '全部方式'
      }, () => {
        this.searchTeachers();
      });
    } catch (error) {
      console.error('解析参数时出错:', error);
      this.setData({ error: '参数解析失败' });
    }
  },

  searchTeachers: function() {
    this.setData({ loading: true, error: null });

    wx.request({
      url: 'http://localhost:8080/teacherGood/search',
      method: 'GET',
      data: {
        goodName: this.data.labels,
        levelName: this.data.rank,
        teacherAddress: this.data.region
      },
      success: (res) => {
        console.log('搜索结果:', res.data);
        if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
          const searchResults = res.data.data.map(item => ({
            ...item,
            goodName: this.formatGoodName(item.goodName)
          }));
          this.setData({ searchResults, loading: false });
        } else {
          console.error('返回的数据格式不正确:', res.data);
          this.setData({ error: '数据格式错误', loading: false });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        this.setData({ 
          error: '搜索失败,请重试', 
          loading: false 
        });
      }
    });
  },

  formatGoodName: function(goodName) {
    if (typeof goodName !== 'string') {
      console.warn('goodName 不是字符串:', goodName);
      return [];
    }
    return goodName.split(',').map(tag => tag.trim()).filter(Boolean);
  },
  onRetry: function() {
    this.searchTeachers();
  },
  navigateToDetails: function(event) {
    const teacherId = event.currentTarget.dataset.teacherId;
    wx.navigateTo({
      url: `/pages/consultDetails/consultDetails?id=${teacherId}`
    });
  },

});
